package com.ts.animal.service.impl;

import com.ts.animal.dao.ExWarningSetDao;
import com.ts.animal.dao.WarningSetDao;
import com.ts.animal.domain.ExWarningSetDO;
import com.ts.animal.domain.WarningSetDO;
import com.ts.animal.service.WarningSetService;
import com.ts.common.utils.Result;
import com.ts.system.util.SystemUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class WarningSetServiceImpl implements WarningSetService {
    @Autowired
    private WarningSetDao warningSetDao;
    @Autowired
    private ExWarningSetDao exWarningSetDao;

    @Override
    public WarningSetDO get(String animalType) {
        return warningSetDao.get(animalType);
    }

    @Override
    public List<WarningSetDO> list(Map<String, Object> map) {
        return warningSetDao.list(map);
    }

    @Override
    public List<ExWarningSetDO> listAll() {
        List<WarningSetDO> warningSetList = warningSetDao.list(null);
        List<ExWarningSetDO> exWarningSetList = warningSetList.stream().map(s -> ExWarningSetDO.getExWarningSetDO(s)).collect(Collectors.toList());
        return exWarningSetList;
    }

    @Override
    public int count(Map<String, Object> map) {
        return warningSetDao.count(map);
    }

    @Override
    public int save(Result result, WarningSetDO warningSet) {
        int ret = warningSetDao.save(warningSet);
        if (ret == 0) {
            result.set(Result.FAIL, "保存失败", null);
        }
        SystemUtil.setWarningSets(warningSets());
        return ret;
    }

    @Override
    public int save(Result result, List<ExWarningSetDO> exWarningSetDOs) {
        exWarningSetDao.removeAll();
        int ret = exWarningSetDao.save(exWarningSetDOs);
        if (ret == 0) {
            result.set(Result.FAIL, "保存失败", null);
        }
        SystemUtil.setWarningSets(warningSets());
        return ret;
    }

    @Override
    public int update(Result result, WarningSetDO warningSet) {
        int ret = warningSetDao.update(warningSet);
        if (ret == 0) {
            result.set(Result.FAIL, "更新失败", null);
        }
        return ret;
    }

    @Override
    public int remove(Result result, String animalType) {
        int ret = warningSetDao.remove(animalType);
        if (ret == 0) {
            result.set(Result.FAIL, "删除失败", null);
        }
        return ret;
    }

    @Override
    public int batchRemove(Result result, String[] animalTypes) {
        int ret = warningSetDao.batchRemove(animalTypes);
        if (ret != animalTypes.length) {
            result.set(Result.FAIL, "部分删除失败", null);
        }
        return ret;
    }

    @Override
    public Map<String, ExWarningSetDO> warningSets() {
        return listAll().stream().collect(Collectors.toMap(ExWarningSetDO::getAnimalVarieties, ExWarningSetDO -> ExWarningSetDO));
    }
}
